// 服务器存储接口//ScratchStorage封包器，包含了默认项目Web sources。
import ScratchStorage from 'scratch-storage';

class Storage extends ScratchStorage {
    constructor () {
        super();
        this.projectHost = '/scratch/projects';
        //this.assetHost = scratchAssetsHost+'/scratch/assets'//在网页中定义scratchAssetsHost
        this.assetHost = `${window.location.protocol}//${window.location.host}/scratch/assets`
    }
    addOfficialScratchWebStores () {
        this.addWebStore(
            [this.AssetType.Project],
            this.getProjectGetConfig.bind(this),
            this.getProjectCreateConfig.bind(this),
            this.getProjectUpdateConfig.bind(this)
        );

        this.addWebStore(
            [this.AssetType.ImageVector, this.AssetType.ImageBitmap, this.AssetType.Sound],
            this.getAssetGetConfig.bind(this),
            // We set both the create and update configs to the same method because
            // storage assumes it should update if there is an assetId, but the
            // asset store uses the assetId as part of the create URI.
            this.getAssetCreateConfig.bind(this),
            this.getAssetCreateConfig.bind(this)
        );
        
        this.addWebStore(
            [this.AssetType.Sound],
            asset => `static/extension-assets/scratch3_music/${asset.assetId}.${asset.dataFormat}`
        );
    }

    getProjectGetConfig (projectAsset) {
        return `${this.projectHost}/${projectAsset.assetId}`;
    }

    getProjectCreateConfig () {
        return {
            url: `${this.projectHost}/`,
            withCredentials: true
        };
    }
    getProjectUpdateConfig (projectAsset) {
        return {
            url: `${this.projectHost}/${projectAsset.assetId}`,
            withCredentials: true
        };
    }

    getAssetGetConfig (asset) {
        // console.error(">>>getAssetGetConfig：", asset);
        return `${this.assetHost}/${asset.assetId}.${asset.dataFormat}`;
    }
    getAssetCreateConfig (asset) {
        // console.error(">>>getAssetCreateConfig：", asset);
        return {
            // There is no such thing as updating assets, but storage assumes it
            // should update if there is an assetId, and the asset store uses the
            // assetId as part of the create URI. So, force the method to POST.
            // Then when storage finds this config to use for the "update", still POSTs
            method: 'post',
            url: `${this.assetHost}/${asset.assetId}.${asset.dataFormat}`,
            withCredentials: true
        };
    }
}

const storage = new Storage();

export default storage;
